package com.scut.dispatching_server.endpoint;

import com.alibaba.fastjson.JSON;
import com.scut.dispatching_server.model.Demand;
import com.scut.dispatching_server.service.DemandCache;
import com.scut.dispatching_server.service.DemandPost;
import com.scut.dispatching_server.service.RelationshipCache;
import com.scut.dispatching_server.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.nio.FloatBuffer;
import java.util.*;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * 声明websocket地址类似Spring MVC中的@controller注解类似，
 * websocket使用@ServerEndpoint来进行声明接口
 */
@ServerEndpoint(value = "/websocket/demand/{demandId}")
@Component
public class DemandEndpoint {


    private static DemandCache demandCache;
    private static DemandPost demandPost;

    private static RelationshipCache relationshipCache;

    private static StatisticsService statisticsService;

    @Autowired
    public void setStatisticsService(StatisticsService statisticsService) {
        DemandEndpoint.statisticsService = statisticsService;
    }


    @Autowired
    public void setRelationshipCache(RelationshipCache relationshipCache) {
        DemandEndpoint.relationshipCache = relationshipCache;
    }

    @Autowired
    public void setDemandCache(DemandCache demandCache) {
        DemandEndpoint.demandCache = demandCache;
    }
    @Autowired
    public void setDemandPost(DemandPost demandPost) {
        DemandEndpoint.demandPost = demandPost;
    }

    private static final Logger sysLogger = Logger.getLogger("sysLog");

    private static Map<String, Session> demandSessions = new HashMap<>();

    public static Map<String, Session> getDemandSessions() {
        return demandSessions;
    }
    @OnOpen
    public void open(Session session,  @PathParam(value = "demandId")String demandId) {
        sysLogger.info("open ------ WebSocket opened from sessionId " + session.getId() + " " + demandId);
        try {
            demandSessions.put(demandId, session);
            session.getBasicRemote().sendText("online");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        sysLogger.info("received ***** WebSocket Received from sessionId " + session.getId() + ": " + message);
        JSONObject r = JSON.parseObject(message);
        if(r.get("type").toString().equals("info")){
            Demand demand = new Demand(r.get("id").toString(), Float.parseFloat(r.get("lon").toString()), Float.parseFloat(r.get("lat").toString()));
            demandCache.saveToCache(demand);
            demandCache.addAliveDemand(demand.getId());
            demandPost.addDemand(demand);
            statisticsService.incrDemandCount();
            return;
        }
        if(r.get("type").toString().equals("cancel")){
            demandCache.deleteDemand(r.get("demand_id").toString());
            ArrayList<String> relationships = relationshipCache.getRelationships();
            for (String relationship : relationships) {
                String[] ids = relationship.split("-");
                if (ids[0].equals(r.get("demand_id").toString())){
                    relationshipCache.deleteRelationship(relationship);
                }
            }
            demandPost.deleteDemand(r.get("demand_id").toString());
            statisticsService.incrExpiredDemandCount();
            return;
        }
    }

    @OnClose
    public void end(Session session) {
        sysLogger.info("closed XXXXX WebSocket closed from sessionId " + session.getId());
        Collection<Session> sessions = demandSessions.values();
        sessions.remove(session);
    }


}
